var wxUtil = require('wxUtil');
var eventConfig = require('eventConfig');
var shareConfig = require('shareConfig');
cc.Class({
    extends: cc.Component,

    properties: {
        lb_score: {
            default: null,
            type: cc.Label
        },
        lb_high: {
            default: null,
            type: cc.Label
        },
        actorStone:{
            default:null,
            type:cc.Prefab
        },
        actorScore:cc.Prefab,
        layGame: {
            default: null,
            type: cc.Node
        },
        nodeActor:{
            default: null,
            type: cc.Node
        },
        sUp:{
            default:null,
            url:cc.AudioClip
        },
        sAddScore:{
            default:null,
            url:cc.AudioClip
        },
        sClick:{
            default:null,
            url:cc.AudioClip
        },
        sBg:{
            default:null,
            url:cc.AudioClip
        },
        sFail:{
            default:null,
            url:cc.AudioClip
        },
        nodeScore: {
            default: null,
            type: cc.Node
        },
        nodeMenu: {
            default: null,
            type: cc.Node
        },
        nodeGameOver: {
            default: null,
            type: cc.Node
        },
        nodeRank: {
            default: null,
            type: cc.Node
        },
        nodeStar:{
            default:null,
            type:cc.Node
        },
        nodeCloud:{
            default:[],
            type:[cc.Node]
        },
        nodeHome:{
            default:[],
            type:[cc.Node]
        },
        nodeFloors: {
            default:[],
            type:[cc.Node]
        },
        spVoice:cc.Sprite,
        sfVoice:[cc.SpriteFrame],
        btnRank:cc.Node,
        btnPlay:cc.Node,
        spLogo:cc.Node,
        nodeFinger:cc.Node,
        nodeCircle:cc.Node,
        nodeGuid:cc.Node,
        btnJumpARSC:cc.Node,
        btnJumpSZYKX:cc.Node,
        btnJumpCWYXP:cc.Node,
        velocity:-3,
        gravity:0.69,
        moveSpace:5,
        volume:0.5,
    },

    onLoad: function () {
        this.score = 0;
        this.high = gGlobal.getHight();
        gGlobal.onGame = false;
        this.setScore();
        this.stones = new Array();
        this.delayTime = 2;
        this.actorX = this.nodeActor.position.x;
        gGlobal.nodeActor = this.nodeActor;
        this.nodeMenu.active = true;
        cc.audioEngine.setEffectsVolume(this.volume);
        this.moveClouds();
        this.moveHouse();
        // this.moveFloor();
        let ani = this.nodeActor.getComponent(cc.Animation);
        if(ani) ani.play();

        let that = this;
        this.nodeGameOver.getComponent('gameOver').setCallFun(function(){
            that.showRank();
        });
        this.initShare();
        //
        this.spLogo.runAction(cc.moveTo(0.25,0,300).easing(cc.easeBackOut(3.0)));
        this.initWx();
        let delayT = gGlobal._random(3, 6);
        this.scheduleOnce(function(){
            this.playLiuxingAni();
        },delayT);
        let voice_status = gGlobal.getVoice();
        let v_id = voice_status ? 0 : 1;
        this.spVoice.spriteFrame = this.sfVoice[v_id];
        if(voice_status)
            this.playBgMusic();
    },

    //微信API测试
    initWx(){
        let show_login_btn_status = gGlobal.getShowLoginBtnStatus();
        console.log('show_login_btn_status:',show_login_btn_status);
        var that = this;
        if(show_login_btn_status == 'true'){
            let button = wxUtil.wxCreateUserInfoBtn();
            button.onTap(function (res) {
                // {errMsg: "getUserInfo:ok", rawData: "{"nickName":"CaiHua","gender":2,"language":"zh_CN"…wXECbdVdxEypIJpxEJlBwScVXNIKsU1FgwDFOpQ0e8w/132"}", userInfo: {…}, signature: "51e0959f1f6a80e1031672c1a64cddfe6fe860ba", encryptedData: "MSjCpAgBrzTpdLFjzG1faa+kXYXE14WPCuTKKs6ahrvIZhOZgV…Hadake4yKFeUXHxAERfxtrXem7EWOacKUgYmyJxGvelZHWUw=", …}
              if(res && res.errMsg == "getUserInfo:ok"){
                    gGlobal.setShowLoginBtnStatus('false');
              }
                button.hide();
                that.actionMenuBtnIn();
              // console.log("wxCreateUserInfoBtn---res:"+JSON.stringify(res));//res 为 json 格式，用户点击"拒绝"或"允许"都会对应不同的数据
            })
        }else{
            this.actionMenuBtnIn();
        }
        wxUtil.showBanner();
    },
    //菜单按钮进入动画
    actionMenuBtnIn(){
        this.btnRank.runAction(cc.moveTo(0.3,0,-176).easing(cc.easeBackOut(3.0)));
        this.btnPlay.runAction(cc.moveTo(0.3,0,-69).easing(cc.easeBackOut(3.0)));
        this.btnJumpARSC.active = true;
        this.btnJumpARSC.runAction(cc.fadeIn(0.3).easing(cc.easeBackOut(3.0)));
        //
        this.btnJumpSZYKX.active = true;
        this.btnJumpSZYKX.runAction(cc.fadeIn(0.3).easing(cc.easeBackOut(3.0)));
        //
        this.btnJumpCWYXP.active = true;
        this.btnJumpCWYXP.runAction(cc.fadeIn(0.3).easing(cc.easeBackOut(3.0)));
    },
    actionMenuBtnOut(){
        var that = this;
        this.btnRank.runAction(cc.moveTo(0.3,-542,-176).easing(cc.easeBackOut(3.0)));
        this.btnJumpARSC.runAction(cc.fadeOut(0.3).easing(cc.easeBackOut(3.0)));
        this.btnJumpCWYXP.runAction(cc.fadeOut(0.3).easing(cc.easeBackOut(3.0)));
        this.btnJumpSZYKX.runAction(cc.fadeOut(0.3).easing(cc.easeBackOut(3.0)));
        this.btnPlay.runAction(cc.sequence(cc.moveTo(0.3,542,-69).easing(cc.easeBackOut(3.0)),cc.callFunc(function () {
            that.nodeMenu.active = false;
        }, this, 0)));

        this.spLogo.runAction(cc.moveTo(0.25,0,773));
    },
    changeVoice(){
        let voice_status = !gGlobal.getVoice();
        gGlobal.setVoice(voice_status);
        let v_id = voice_status ? 0 : 1;
        this.spVoice.spriteFrame = this.sfVoice[v_id];
        console.log("-----changeVoice:",gGlobal.gVoice);
        if(gGlobal.gVoice){
            // cc.audioEngine.play(this.sClick,false);
            this.playBgMusic();
        }else{
            this.stopBgMusic();
        }
    },
    playBgMusic(){
        this.stopBgMusic();
        var audioID = cc.audioEngine.playMusic(this.sBg, true);
    },
    stopBgMusic(){
        cc.audioEngine.stopMusic();
    },
    update: function (dt) {
        if(gGlobal.onGame){
            this.velocity -= this.gravity;
            this.nodeActor.y += this.velocity;
            this.nodeActor.y = this.nodeActor.y > 536 ? 536 : this.nodeActor.y;
            // this.nodeActor.rotation += 5;
            // this.nodeActor.rotation = this.nodeActor.rotation > 60 ? 60 :this.nodeActor.rotation;
            // this.nodeActor.y = this.nodeActor.y < -339 ? -339 : this.nodeActor.y;
            gGlobal.actorP = this.nodeActor.position;

            let boxBird = this.nodeActor.getBoundingBox();
            //碰到地面游戏结束
            let floor1Box = this.nodeFloors[0].getBoundingBox();
            let floor2Box = this.nodeFloors[1].getBoundingBox();
            if(cc.Intersection.rectRect(boxBird,floor1Box) || cc.Intersection.rectRect(boxBird,floor2Box)){
                this.gameOver();
            }
        }
        //移动地板
        this.nodeFloors[0].x -= this.moveSpace;
        this.nodeFloors[1].x -= this.moveSpace;
        if(this.nodeFloors[0].x <= -720){
            this.nodeFloors[0].x = this.nodeFloors[1].x + 800-1
        }
        if(this.nodeFloors[1].x <= -720){
            this.nodeFloors[1].x = this.nodeFloors[0].x + 800-1;
        }
    },

    moveHouse(){
        for(let i=0;i<this.nodeHome.length;i++){
            let house1 = this.nodeHome[i];
            let x = house1.position.x;
            let y = house1.position.y;
            let time = ((x+672)/1134)*10;
            cc.log("moveHouse--i:"+time);
            let move1 = cc.moveTo(time,cc.v2(-672, y));
            var that = this;
            house1.runAction(cc.sequence(move1,cc.callFunc(function(target, id){
                cc.log("moveHouse--callFunc--id:"+id);
                that.moveHouseById(id);
            },this,i)));
        }
    },
    moveHouseById(id){
        let house = this.nodeHome[id];
        let time = 10;
        let y = house.position.y;
        house.setPosition(cc.p(672,y));
        let move1 = cc.moveTo(time,cc.v2(-672, y));
        var that = this;
        house.runAction(cc.sequence(move1,cc.callFunc(function(){
            that.moveHouseById(id);
        },this,1)));
    },
    //移动云朵
    moveClouds:function(id){
        for(let i=0;i<this.nodeCloud.length;i++){
            let cloud1 = this.nodeCloud[i];
            let x = cloud1.position.x;
            let y = cloud1.position.y;
            let time = ((x+420)/840)*50;
            cc.log("moveClouds--i:"+time);
            let move1 = cc.moveTo(time,cc.v2(-420, y));
            var that = this;
            cloud1.runAction(cc.sequence(move1,cc.callFunc(function(target, id){
                cc.log("moveClouds--callFunc--id:"+id);
                that.moveCloudById(id);
            },this,i)));
        }
    },

    moveCloudById:function(id){
        let cloud = this.nodeCloud[id];
        let time = 50;
        let y = cloud.position.y;
        cloud.setPosition(cc.p(420,y));
        let move1 = cc.moveTo(time,cc.v2(-420, y));
        var that = this;
        cloud.runAction(cc.sequence(move1,cc.callFunc(function(){
            that.moveCloudById(id);
        },this,1)));
    },

    startGame:function(){
        this.actionMenuBtnOut();
        this.nodeScore.active = true;
        if(gGlobal.gVoice)
            cc.audioEngine.play(this.sClick,false);
        //
        this.showOrHideGuid(true);
    },

    btnGuid(){
        this.showOrHideGuid(false);
        this.scheduleOnce(function(){
            this.addPip();
            },
        );
    },
    showOrHideGuid(isShow){
        var that = this;
        that.nodeCircle.stopAllActions();
        that.nodeGuid.stopAllActions();
        that.nodeFinger.stopAllActions();
        if(isShow){
            this.nodeGuid.active = true;
            this.nodeGuid.runAction(cc.sequence(cc.fadeIn(0.2),cc.callFunc(function(){
                that.nodeCircle.runAction(
                    cc.repeatForever(
                        cc.sequence(
                            cc.scaleTo(0.12,1,1),cc.scaleTo(0.12,0.8,0.8),cc.delayTime(1))));
                that.nodeFinger.runAction(
                    cc.repeatForever(
                        cc.sequence(
                            cc.scaleTo(0.12,0.9,0.9),cc.scaleTo(0.12,1.35,1.35),cc.delayTime(1))));
            },this,1)));
        }else{
            this.nodeGuid.active = false;
            this.nodeGuid.runAction(cc.fadeOut(0.15));
            gGlobal.onGame = true;
        }
    },
    clickGameView:function(){
        if(gGlobal.onGame){
            this.velocity = 8;
            if(gGlobal.gVoice)
                cc.audioEngine.play(this.sUp,false);
            // this.nodeActor.rotation -= 10;
            // this.nodeActor.rotation = this.nodeActor.rotation < -60 ? -60 :this.nodeActor.rotation;
        }
    },

    addPip:function(){
        var aStoneUp = cc.instantiate(this.actorStone);
        var aStoneDown = cc.instantiate(this.actorStone);
        var aScore = cc.instantiate(this.actorScore);
        let scoreSize = aScore.getContentSize();
        let sSize = aStoneUp.getContentSize();
        let sHeight = 1136;
        let sWidth = 640;
        let that = this;
        aStoneUp.getComponent('actorStone').setInfo(function(){
            that.gameOver();
        });
        this.layGame.addChild(aStoneUp);
        this.stones.push(aStoneUp);
        aStoneDown.getComponent('actorStone').setInfo(function(){
            that.gameOver();
        });
        aStoneDown.rotation = 180;
        this.layGame.addChild(aStoneDown);
        this.stones.push(aStoneDown);
        let maxUpY = sHeight / 2;
        let minUpY = sHeight / 3;
        let y1 = gGlobal._random(minUpY,maxUpY);
        let space = gGlobal._random(250,350);
        aScore.setContentSize(scoreSize.width,space-50);
        aScore.getComponent('actorScore').setCallFun(function(){
            that.addScore();
        });
        this.layGame.addChild(aScore);
        let y2 = y1 - sSize.height - space;
        let x = sWidth + sSize.width / 2 + 0;
        let s_y = y1 - sSize.height/2 - space/2;
        aStoneUp.setPosition(cc.p(x, y1));
        aStoneDown.setPosition(cc.p(x, y2));
        aScore.setPosition(cc.p(x,s_y));
        let time = 3.8;
        let moveEndX = -400;
        aStoneUp.runAction(cc.sequence(cc.moveTo(time,cc.v2(moveEndX, y1)),cc.removeSelf()));
        aStoneDown.runAction(cc.sequence(cc.moveTo(time,cc.v2(moveEndX, y2)),cc.removeSelf()));
        aScore.runAction(cc.sequence(cc.moveTo(time,cc.v2(moveEndX, s_y)),cc.removeSelf()));

        this.scheduleOnce(function(){
            this.addPip();
            },this.delayTime
        );
    },

    gameOver:function(info){
        gGlobal.onGame = false;
        this.nodeScore.active = false;
        if(gGlobal.gVoice)
            cc.audioEngine.play(this.sFail,false);
        cc.log("----gameOver");
        this.nodeGameOver.getComponent('gameOver').setShow(this.score);
        this.nodeActor.stopAllActions();
    },

    setScore:function(){
        this.lb_score.string = "分数: "+this.score;
        this.lb_high.string = "最高: "+this.high;
    },

    addScore:function(){
        this.score += 1;
        if(gGlobal.gVoice)
            cc.audioEngine.play(this.sAddScore,false);
        if(this.score > this.high){
            this.high = this.score;
            gGlobal.saveHight(this.high);
        }
        this.setScore();
    },

    showRank:function(){
        // console.log('game--showRank');
        if(gGlobal.gVoice)
            cc.audioEngine.play(this.sClick,false);
        this.nodeRank.getComponent('dlgRank').setShow();
    },

    // 流星动画
    playLiuxingAni:function() {
        // cc.log("---流星动画:",this.nodeStar);
        if (this.nodeStar) {
            this.nodeStar.active = true;
            var ani = this.nodeStar.getComponent(cc.Animation);
            // cc.log("---ani:",ani);
            if (ani) {
                ani.play();

                ani.on('finished', function () {
                    // cc.log("---finished---");
                    // this.nodeStar.active = false;
                }, this);
            }
        }
        let delayT = gGlobal._random(3, 5);
        this.scheduleOnce(function(){
            this.playLiuxingAni();
        },delayT);
    },

    initShare:function(){
        // console.log('game--initShare');
        wxUtil.showShareMenu();
        let url = shareConfig.url;
        wxUtil.onShareAppMessage(shareConfig.list[1].s_txt,url+shareConfig.list[1].s_url);
    },

    onDestroy(){
        // wx.hideShareMenu();
        this.stopBgMusic();
    },
});
